<?php
namespace Admin\Controller;
use Admin\Controller;
/**
 * 分类管理
 */
class CategoryController extends BaseController
{
    /**
     * 分类列表
     * @return [type] [description]
     */
    public function index($key="")
    {
        if($key == ""){
            $model = M('category');  
        }else{
            $where['en_name'] = array('like',"%$key%");
            $where['zh_name'] = array('like',"%$key%");
            $where['_logic'] = 'or';
            $model = M('category')->where($where); 
        }
        $count      = $model->where($where)->count();// 查询满足要求的总记录数
        $Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $this->page = $Page->show();// 分页显示输出
        $this->category = $model->limit($Page->firstRow.','.$Page->listRows)->where($where)->order('id ASC')->select();

        $this->display();   
    }

    /**
     * 添加分类
     */
    public function add()
    {
        //默认显示添加表单
        if (IS_POST) {
            $zh_name = I('post.zh_name');
            $en_name = I('post.en_name');

            //如果用户提交数据
            $model = M("Category");

            //判断类型是否存在
            $where['en_name'] = $en_name;
            $where['zh_name'] = $zh_name;
            $where['_logic'] = 'or';
            $res = $model->where($where)->find();
            if($res){
                $this->error("该分类已存在");
            }


            $model->zh_name = $zh_name;
            $model->en_name = $en_name;
            $model->icon = I('post.icon');

            if ($model->add()) {
                $this->success("分类添加成功");
            } else {
                $this->error("分类添加失败");
            }

        }else{
            $this->display();
        }
    }
    /**
     * 更新分类信息
     * @param  [type] $id [分类ID]
     * @return [type]     [description]
     */
    public function update()
    {
        //默认显示添加表单
        if (!IS_POST) {
            $this->info = M('category')->find(I('id'));
            $this->display();
        }
        if (IS_POST) {
            $model = M('category');
            $model->zh_name = I('post.zh_name');
            $model->en_name = I('post.en_name');
            $model->icon    = I('post.icon');

            if ($model->where(array('id' => I('id')))->save()) {
                $this->success("分类更新成功", U('category/index'));
            } else {
                $this->error("分类更新失败");
            }
        }
    }
    /**
     * 删除分类
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function delete($id)
    {
        $model = M('category');
        //查询属于这个分类的文章
        $demos = M('demos')->where('type='.$id)->select();
        if($demos){
            $this->error("禁止删除含有案例的分类");
        }

        //验证通过
        $result = $model->delete($id);
        if($result){
            $this->success("分类删除成功", U('category/index'));
        }else{
            $this->error("分类删除失败");
        }
    }
}
